﻿var MAPFILES_URL = "http://www.google.com/mapfiles/";
var AddressType = 1;
var map = null;
var markers = null;
var polylines = null;
var bounds = null;
var info = null;
var details = null;
var selected = null;
var reverseIcon = null;
var clickMarker = null;
var hashFragment = "";
var searchAddress = "";
var CurrentLat;
var CurrentLng;
var CurrentTitle;
var GGeoStatusCode = {
    "200": "G_GEO_SUCCESS",
    "400": "G_GEO_BAD_REQUEST",
    "500": "G_GEO_SERVER_ERROR",
    "601": "G_GEO_MISSING_QUERY",
    "602": "G_GEO_UNKNOWN_ADDRESS",
    "603": "G_GEO_UNAVAILABLE_ADDRESS",
    "604": "G_GEO_UNKNOWN_DIRECTIONS",
    "610": "G_GEO_BAD_KEY",
    "620": "G_GEO_TOO_MANY_QUERIES"
};

var GGeoStatusDescription = {
    "200": "Tìm kiếm thành công. Kết quả hiện thị bên dưới.",
    "400": "Địa điểm nhập vào chưa chính xác.",
    "500": "Địa điểm nhập vào chưa chính xác,<br/>Chưa biết nguyên nhân lỗi.",
    "601": "The HTTP q parameter was either missing or had no value.<br/>For geocoding requests, this means that an empty address was specified as input.</br>For directions requests, this means that no query was specified in the input.",
    "602": "No corresponding geographic location could be found for the specified address.<br/>This may be due to the fact that the address is relatively new, or it may be incorrect.",
    "603": "The geocode for the given address or the route for the given<br/>directions query cannot be returned due to legal or contractual reasons.",
    "604": "The GDirections object could not compute directions between the points mentioned in the query.<br/>This is usually because there is no route available between the two points, or because we do not have data for routing in that region.",
    "610": "The given key is either invalid or does not match the domain for which it was given.",
    "620": "The given key has gone over the requests limit in the 24 hour period."
};

var GGeoAddressAccuracy = {
    "0": "Unknown location.",
    "1": "Country",
    "2": "Region<br/>(state, province, prefecture, etc.) ",
    "3": "Sub-region<br/>(county, municipality, etc.)",
    "4": "Town (city, village)",
    "5": "Post code (zip code)",
    "6": "Street level accuracy.",
    "7": "Intersection level accuracy.",
    "8": "Address level accuracy.",
    "9": "Premise<br/>(building name, property name, shopping center, etc.)"
}



function initialize() {
    var params = parseUrlParams();
    clearOptions();
    setOptions(params);
    var latlng = new google.maps.LatLng(10.781414211927238, 106.70711517333984);
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        $('#map_canvas').width(screen.width);
        map.setCenter(params.center ? params.center : latlng);
        map.setZoom(params.zoom ? params.zoom : 15);
        map.setUIToDefault();

        reverseIcon = new GIcon(G_DEFAULT_ICON);
        reverseIcon.image = MAPFILES_URL + "dd-start.png";

        GEvent.addListener(map, "click", function (overlay, latlng) {
            if (!overlay) {
                document.getElementById("keyword").value = latlng.toUrlValue(6);
                reverseGeocode(latlng);
            }
        });

        if (document.getElementById("keyword").value) {
            geocode();
        }
    }
    setInterval(checkHashFragment, 210);
    $('#map_canvas').width(screen.width - 270);
    InitFunctions();

}


function tim() {

    var address = document.getElementById('keyword').value;
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(
        address,
        function (point) {
            if (!point) {
                alert(address + " không tìm thấy địa chỉ!");
            }
            else {
                var latlng = new google.maps.LatLng(point.y, point.x);                
                map = new google.maps.Map(document.getElementById('map_canvas'), {
                    center: latlng,
                    zoom: 15,
                    mapTypeId:'roadmap'
                });

                var request = {
                    location: latlng,
                    radius: '500',
                    types: ['trạm xe bus']
                };
                var infowindow = new google.maps.InfoWindow();
                var service = new google.maps.places.PlacesService(map);
                service.search(request, callback);
            }

        })
}

function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
            var place = results[i];
            createMarker(results[i]);
        }
    }
}
function createMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
        
        
    });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
    });
}

function ProcessEnter(e) {
    //if(!e) var e = window.event;
    if (e.keyCode != 13) return;
    document.getElementById("keyword").blur();
    geocode(document.getElementById("keyword").value);
}
function checkHashFragment() {
    if (unescape(window.location.hash) != unescape(hashFragment)) {
        var params = parseUrlParams();
        clearOptions();
        setOptions(params);

        if (params.zoom && params.center) {
            map.setZoom(params.zoom);
            map.setCenter(params.center);
        }

        if (document.getElementById("keyword").value) {
            geocode();
        }
    }
}

function parseUrlParams() {
    var params = {};

    if (window.location.search) {
        params.query = unescape(window.location.search.substring(1));
    }

    if (window.location.hash) {
        hashFragment = unescape(window.location.hash);
        var args = hashFragment.substring(1).split('&');
        for (var i in args) {
            var param = args[i].split('=');
            switch (param[0]) {
                case 'q':
                    params.query = unescape(param[1]);
                    break;
                case 'vpcenter':
                    var center = parseLatLng(param[1]);
                    if (center != null) {
                        params.center = center;
                    }
                    break;
                case 'vpzoom':
                    var zoom = parseInt(param[1]);
                    if (!isNaN(zoom)) {
                        params.zoom = zoom;
                    }
                    break;
                case 'country':
                    params.country = unescape(param[1]);
                    break;
            }
        }
    }

    return params;
}

function clearOptions() {
    document.getElementById("keyword").value = "";
    //document.getElementById("biasViewport").checked = false;
    //document.getElementById("country").value = "";
}

function setOptions(params) {
    if (params.query) {
        document.getElementById("keyword").value = params.query;
    }

    if (params.zoom && params.center) {
        document.getElementById("biasViewport").value = true;
    }

    if (params.country) {
        document.getElementById("country").value = params.country;
    }
}

function geocode() {
    var query = document.getElementById("keyword").value;
    searchAddress = query;
    if (/\s*^\-?\d+(\.\d+)?\s*\,\s*\-?\d+(\.\d+)?\s*$/.test(query)) {
        var latlng = parseLatLng(query);
        if (latlng == null) {
            document.getElementById("keyword").value = "";
        } else {
            reverseGeocode(latlng);
        }
    } else {
        forwardGeocode(query);
    }
}

function initGeocoder(query) {
    selected = null;
    map.clearOverlays();

    var hash = 'q=' + query;
    var vpbias = document.getElementById("biasViewport").checked;
    var country = document.getElementById("country").value;
    var geocoder = new GClientGeocoder();

    if (vpbias) {
        hash += '&vpcenter=' + map.getCenter().toUrlValue(6);
        hash += '&vpzoom=' + map.getZoom();
        geocoder.setViewport(map.getBounds());
    }

    if (country) {
        hash += '&country=' + country;
        geocoder.setBaseCountryCode(country);
    }

    hashFragment = '#' + escape(hash);
    window.location.hash = escape(hash);
    return geocoder;
}

function forwardGeocode(address) {
    var geocoder = initGeocoder(address);
    geocoder.getLocations(address, function (response) {
        showResponse(response, false);
    });
}

function reverseGeocode(latlng) {
    var geocoder = initGeocoder(latlng.toUrlValue(6));
    geocoder.getLocations(latlng, function (response) {
        showResponse(response, true);
    });
    map.panTo(latlng);
    map.addOverlay(new GMarker(latlng, { 'icon': reverseIcon }));
}

function parseLatLng(value) {
    value.replace('/\s//g');
    var coords = value.split(',');
    var lat = parseFloat(coords[0]);
    var lng = parseFloat(coords[1]);
    if (isNaN(lat) || isNaN(lng)) {
        return null;
    } else {
        return new GLatLng(lat, lng);
    }
}

function showResponse(response, reverse) {
    if (!response) {
        alert("Geocoder request failed");
    } else {

        if (response.Status.code == 200) {
            plotMatchesOnMap(response, reverse);
        } else {
            //document.getElementById("keyword").value = "";
            if (!reverse) {
                map.setCenter(new GLatLng(0.0, 0.0), 1);
            }
        }
    }
}

function plotMatchesOnMap(response, reverse) {
    var resultCount = response.Placemark.length;

    info = new Array(resultCount);
    details = new Array(resultCount);
    markers = new Array(resultCount);
    polylines = new Array(resultCount);
    bounds = new Array(resultCount);

    var icons = new Array(resultCount);
    var latlngs = new Array(resultCount);

    var infoListHtml = "";
    GetLatLng(response.Placemark[0]);
    for (var i = 0; i < resultCount; i++) {
        icons[i] = new GIcon(G_DEFAULT_ICON);
        icons[i].image = MAPFILES_URL + "marker" + String.fromCharCode(65 + i) + ".png";
        latlngs[i] = new GLatLng(response.Placemark[i].Point.coordinates[1],
                             response.Placemark[i].Point.coordinates[0]);
        markers[i] = new GMarker(latlngs[i], { icon: icons[i] });
        //polylines[i] = getPolyline(response.Placemark[i]);
        bounds[i] = getBounds(response.Placemark[i]);
        info[i] = getInfoHtml(response.Placemark[i]);
        details[i] = getAddressDetailHtml(response.Placemark[i]);

        infoListHtml += getInfoListItem(i, icons[i].image, info[i]);
    }

    if (!reverse) {
        zoomToBounds(bounds, map);
    }

    for (var i = 0; i < resultCount; i++) {
        map.addOverlay(markers[i]);
        addInfoWindowListener(i, markers[i], details[i]);
    }

    GEvent.trigger(markers[0], "click");
}

function getInfoListItem(i, iconUrl, info) {
    var html = '<a onclick="selectMarker(' + i + ')">';
    html += '<div class="info" id="p' + i + '">';
    html += '<table><tr valign="top">';
    html += '<td style="padding: 2px"><img src="' + iconUrl + '"/></td>';
    html += '<td style="padding: 2px">' + info + '</td>';
    html += '</tr></table>';
    html += '</div></a>';
    return html;
}

function selectMarker(n) {
    GEvent.trigger(markers[n], "click");
}

function zoomToBounds(bounds, map) {
    var b = new GLatLngBounds();

    for (var i = 0; i < markers.length; i++) {
        b.extend(bounds[i].getSouthWest());
        b.extend(bounds[i].getNorthEast());
    }

    var center = b.getCenter();
    var zoom = map.getBoundsZoomLevel(b);
    map.setCenter(center, zoom);
}

function addInfoWindowListener(i, marker, details) {
    GEvent.addListener(marker, "click", function () {
        if (selected != null) {
            document.getElementById('p' + selected).style.backgroundColor = "white";
            map.removeOverlay(polylines[selected]);
        }
        var zoomDelta = map.getBoundsZoomLevel(bounds[i]) - map.getZoom();
        if (zoomDelta < 0 || zoomDelta > 5) {
            map.setZoom(map.getBoundsZoomLevel(bounds[i]));
        }
        marker.openInfoWindowHtml(details);
        if (!map.getBounds().containsBounds(bounds[i])) {
            map.zoomOut();
            map.panTo(bounds[i].getCenter());
        }
        map.addOverlay(polylines[i]);
        document.getElementById('p' + i).style.backgroundColor = "#eeeeff";
        document.getElementById('matches').scrollTop = document.getElementById('p' + i).offsetTop - document.getElementById('matches').offsetTop;
        selected = i;
    });
}

function getPolyline(placemark) {
    var ne = new GLatLng(placemark.ExtendedData.LatLonBox.north, placemark.ExtendedData.LatLonBox.east);
    var se = new GLatLng(placemark.ExtendedData.LatLonBox.south, placemark.ExtendedData.LatLonBox.east);
    var sw = new GLatLng(placemark.ExtendedData.LatLonBox.south, placemark.ExtendedData.LatLonBox.west);
    var nw = new GLatLng(placemark.ExtendedData.LatLonBox.north, placemark.ExtendedData.LatLonBox.west);
    var polyline = new GPolyline([ne, se, sw, nw, ne], '#ff0000', 2, 1.0);
    return polyline;
}

function getBounds(placemark) {
    var ne = new GLatLng(placemark.ExtendedData.LatLonBox.north, placemark.ExtendedData.LatLonBox.east);
    var sw = new GLatLng(placemark.ExtendedData.LatLonBox.south, placemark.ExtendedData.LatLonBox.west);
    var bounds = new GLatLngBounds(sw, ne);
    return bounds;
}

function getInfoHtml(placemark) {
    var html = '<table class="tabContent">';
    html += tr('Address', placemark.address);
    html += tr('Coordinates', latlngtxt(placemark.Point.coordinates));
    html += tr('Bounds', boundstxt(placemark.ExtendedData.LatLonBox));
    html += tr('Accuracy', accuracytxt(placemark.AddressDetails.Accuracy));
    html += '</table>';
    return html;
}
function GetLatLng(placemark) {
    var coordinates = placemark.Point.coordinates;
    CurrentLat = coordinates[1];
    CurrentLng = coordinates[0];
}
function getAddressDetailHtml(placemark) {
    return html = '<table class="tabContent">' + getAddressDetailDt(placemark.AddressDetails) + '</table>';
}
function ha() {
    alert('hhaa');
}
function getAddressDetailDt(feature) {
    var address = document.getElementById('keyword').value;
    var html = '';
    html += '<h2>Địa chỉ cần tìm </h2>'
    if ("" != address) {
        html += '<p>' + address + '</p>';
        html += 'Tìm ';
        html += '<select style="width:100px;">';
        html += '<option value="">Vui lòng chọn chuyên mục</option>';
        html += '<option value="2">Cây xăng</option>';
        html += '<option value="3">Ga ra</option>';
        html += '<option value="10">Show room</option>';
        html += '<option value="11">ATM</option>';
        html += '</select>';
        html += '<a href="#?w=440" rel="popup_name2" class="poplight" alt="Tìm xung quanh"style="color:Black;padding-left: 20px" onclick="ha();">Tìm xung quanh</a>';

    }
    else
        html += '<p>' + searchAddress + '</p>';
    //      for (var key in feature) {
    //        if (feature[key] instanceof Array) {
    //          html += tr(key, feature[key][0]);
    //        } else if (feature[key] instanceof Object) {
    //          html += getAddressDetailDt(feature[key]);
    //        } else {
    //          html += tr(key, feature[key]);
    //        }
    //      }
    //    InitFunctions();
    return html;
}

function tr(key, value) {
    return '<tr><td style="text-align: right; font-weight: bold; vertical-align: top; white-space: nowrap;">' + key + ':</td><td>' + value + '</td></tr>';
}

function latlngtxt(coordinates) {
    return '(' + coordinates[1] + ', ' + coordinates[0] + ')';
}

function boundstxt(latlonbox) {
    return latlngtxt([latlonbox.west, latlonbox.south]) + ' - ' + latlngtxt([latlonbox.east, latlonbox.north]);
}

function accuracytxt(accuracy) {
    return accuracy + ' - ' + GGeoAddressAccuracy[accuracy];
}
/*  Custome */
function SetAdressType(value) {
    AddressType = value;
    if (7 == value) $('#titlesearch').html('Chọn khu vực chỗ đậu xe');
    else if (1 == value) $('#titlesearch').html('Chọn khu vực có cây xăng xe');
    else if (3 == value) $('#titlesearch').html('Chọn khu vực có show room');
    else if (2 == value) $('#titlesearch').html('Chọn khu vực có gara');
}
function GetDistrict(CityId) {

    var webMethod = '/map.asmx/GetDistricts'
    var parameters = "{'CityId':'" + CityId + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<option value="' + data[i].Id + '">' + data[i].Name + '</option>';
                }
            });
            $("#DistrictId").empty().html(result);
        },
        error: function (e) {
            $("#DistrictId").html("Unavailable");
        }
    });
};
function GetDistrict1(CityId) {

    var webMethod = '/map.asmx/GetDistricts'
    var parameters = "{'CityId':'" + CityId + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<option value="' + data[i].Id + '">' + data[i].Name + '</option>';
                }
            });
            $("#DistrictId1").empty().html(result);
        },
        error: function (e) {
            $("#DistrictId1").html("Unavailable");
        }
    });
};
function GetWard(DistrictId) {
    var webMethod = '/map.asmx/GetWards'
    var parameters = "{'DistrictId':'" + DistrictId + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<option value="' + data[i].Id + '">' + data[i].Name + '</option>';
                }
            });
            $("#WardId").empty().html(result);
        },
        error: function (e) {
            $("#WardId").html("Unavailable");
        }
    });
};
function GetWard1(DistrictId) {
    var webMethod = '/map.asmx/GetWards'
    var parameters = "{'DistrictId':'" + DistrictId + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<option value="' + data[i].Id + '">' + data[i].Name + '</option>';
                }
            });
            $("#WardId1").empty().html(result);
        },
        error: function (e) {
            $("#WardId1").html("Unavailable");
        }
    });
};
function GetStreet(DistrictId, WardId) {
    var webMethod = '/map.asmx/GetStreets'
    var parameters = "{'DistrictId':'" + DistrictId + "','WardId':'" + WardId + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<option value="' + data[i].Id + '">' + data[i].Name + '</option>';
                }
            });
            $("#StreetId").empty().html(result);
        },
        error: function (e) {
            $("#StreetId").html("Unavailable");
        }
    });
};
function GetStreet1(DistrictId, WardId) {
    var webMethod = '/map.asmx/GetStreets'
    var parameters = "{'DistrictId':'" + DistrictId + "','WardId':'" + WardId + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<option value="' + data[i].Id + '">' + data[i].Name + '</option>';
                }
            });
            $("#StreetId1").empty().html(result);
        },
        error: function (e) {
            $("#StreetId1").html("Unavailable");
        }
    });
};
function GetAddress(StreeId, AddressType) {
    var webMethod = '/map.asmx/GetAddress'
    var parameters = "{'StreeId':'" + StreeId + "','AddressType':'" + AddressType + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<li onclick="SetMaker(' + data[i].Lat + ',' + data[i].Lon + ",'" + data[i].Name + "');\">" + data[i].Name + '</li>';
                }
            });
            $("#Addresses").empty().html(result);
        },
        error: function (e) {
            $("#Addresses").html("Unavailable");
        }
    });
};
function GetAddressByWard(WardId, AddressType) {
    var webMethod = '/map.asmx/GetAddressByWard'
    var parameters = "{'WardId':'" + WardId + "','AddressType':'" + AddressType + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<li onclick="SetMaker(' + data[i].Lat + ',' + data[i].Lon + ",'" + data[i].Name + "');\">" + data[i].Name + '</li>';

                }
            });
            $("#Addresses1").empty().html(result);
        },
        error: function (e) {
            $("#Addresses1").html("Unavailable");
        }
    });
};
function GetAddressByWard1(WardId, AddressType) {
    var webMethod = '/map.asmx/GetAddressByWard'
    var parameters = "{'WardId':'" + WardId + "','AddressType':'" + AddressType + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<li onclick="SetMaker(' + data[i].Lat + ',' + data[i].Lon + ",'" + data[i].Name + "');\">" + data[i].Name + '</li>';

                }
            });
            $("#Addresses").empty().html(result);
        },
        error: function (e) {
            $("#Addresses").html("Unavailable");
        }
    });
};
function GetAddressType() {
    var webMethod = '/map.asmx/GetAddressType'
    var parameters = "";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<option value="' + data[i].Id + '">' + data[i].Name + '</option>';
                }
            });
            $("#AddressTypeId").empty().html(result);
        },
        error: function (e) {
            $("#AddressTypeId").html("Unavailable");
        }
    });
};
function GetFavoriteAddress(AddressTypeId, StreetId) {
    var webMethod = '/map.asmx/GetFavoriteAddress'
    var parameters = "{'AddressTypeId':'" + AddressTypeId + "','StreetId':'" + StreetId + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var i = 0;
            var result = "";
            $.each(msg, function (key, val) {
                var data = jQuery.parseJSON(val);
                for (i = 0; i < data.length; i++) {
                    result += '<li onclick="SetMaker(' + data[i].Lat + ',' + data[i].Lon + ",'" + data[i].Name + "');\">" + data[i].Name + '</li>';

                }
            });
            $("#Addresses").empty().html(result);
        },
        error: function (e) {
            $("#Addresses").html("Unavailable");
        }
    });
};


function SendMail(name, sender, receive, subject, content, lat, lng) {
    var webMethod = '/map.asmx/SendEmail'
    var parameters = "{'SendFrom':'" + sender + "','SendTo':'" + receive + "','Subject':'" + subject + "','Body':'" + content + "','Lat':'" + lat + "','Lng':'" + lng + "','Name':'" + name + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            $("#errors").empty().html(msg.d);
        },
        error: function (e) {
            $("#errors").html("Unavailable");
        }
    });
};
function AddAddress(OwnerCompany, Name, Phone, Fax, Email, Website, TypeId, StreetId, Road, Address, Lat, Lng) {
    var webMethod = '/map.asmx/AddAddress'
    var parameters = "{'OwnerCompany':'" + OwnerCompany + "','Name':'" + Name + "','Phone':'" + Phone + "','Fax':'" + Fax + "','Email':'" + Email + "','Website':'" + Website + "','TypeId':'" + TypeId + "','StreetId':'" + StreetId + "','Road':'" + Road + "','Address':'" + Address + "','Lat':'" + Lat + "','Lng':'" + Lng + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert(msg.d);
            //            $("#errors1").empty().html(msg.d);
        },
        error: function (e) {
            $("#errors1").html("Unavailable");
        }
    });
};
//function AddAddress(name, address, Street, StreetId, WardId, DistrictId, Type, Lat, Lng) {
//    var webMethod = '/map.asmx/AddAddress'
//    var parameters = "{'Name':'" + name + "','Address':'" + address + "','StreetId':'" + StreetId + "','WardId':'" + WardId + "','DistrictId':'" + DistrictId + "','Street':'" + Street + "','Lat':'" + Lat + "','Lng':'" + Lng + "','Type':'" + Type + "'}";
//    $.ajax({
//        type: "POST",
//        url: webMethod,
//        data: parameters,
//        contentType: "application/json; charset=utf-8",
//        dataType: "json",
//        success: function (msg) {

//            $("#errors1").empty().html(msg.d);
//        },
//        error: function (e) {
//            $("#errors1").html("Unavailable");
//        }
//    });
//};
function SetMaker(lat, lon, desc) {
    map.setUIToDefault();
    var latlng = new google.maps.LatLng(lat, lon);
    var marker = new GMarker(latlng);
    map.addOverlay(marker);
    var myHtml = desc;
    map.openInfoWindowHtml(latlng, myHtml);
    map.setCenter(latlng, 15);
}
function MiniMaxi(max) {
    if (max) {
        document.getElementById('leftpanel').width = '11px';
        alert('haha');
    } else {
        document.getElementById('leftpanel').width = '10px';


    }

}

function TypeChange() {
    var id = document.getElementById('AddressTypeId1');
    GetFavoriteAddress(id.value);
}
function CityChange() {
    var id = document.getElementById('ProvinceId');
    GetDistrict(id.value);
};
function CityChange1() {
    var id = document.getElementById('ProvinceId1');
    GetDistrict1(id.value);
};
function DistrictChange() {
    var id = document.getElementById('DistrictId');
    GetWard(id.value);
}
function DistrictChange1() {
    var id = document.getElementById('DistrictId1');
    GetWard1(id.value);
}
function WardChange() {
    var DistrictId = document.getElementById('DistrictId');
    var WardId = document.getElementById('WardId');
    GetStreet(DistrictId.value, WardId.value);
    GetAddressByWard(WardId.value, AddressType);
}
function WardChange1() {
    var DistrictId = document.getElementById('DistrictId1');
    var WardId = document.getElementById('WardId1');
    GetStreet1(DistrictId.value, WardId.value);
    GetAddressByWard1(WardId.value, AddressType);
}
function StreetChange() {
    var id = document.getElementById('StreetId');
    GetAddress(id.value, AddressType);

    var ProvinceId = document.getElementById('ProvinceId');
    var DistrictId = document.getElementById('DistrictId');
    var WardId = document.getElementById('WardId');
    var StreetId = document.getElementById('StreetId');

    GetByProvinceId(ProvinceId.value);
    GetByDistrictId(DistrictId.value);
    GetByQuarterId(WardId.value);
    GetById(StreetId.value);

}
function SendEmailAction() {
    var name = document.getElementById('senderName');
    var sender = document.getElementById('senderEmail');
    var receive = document.getElementById('receiveEmails');
    var content = document.getElementById('ContentEmails');
    var subject = document.getElementById('Subject');
    SendMail(name.value, sender.value, receive.value, subject.value, content.value, CurrentLat, CurrentLng);
}
function geocode1() {
    var query = document.getElementById("Street").value;
    searchAddress = query;
    if (/\s*^\-?\d+(\.\d+)?\s*\,\s*\-?\d+(\.\d+)?\s*$/.test(query)) {
        var latlng = parseLatLng(query);
        if (latlng == null) {
            document.getElementById("Street").value = "";
        } else {
            reverseGeocode(latlng);
        }
    } else {
        forwardGeocode(query);
    }
}


function test() {
    
    var ProvinceId = document.getElementById('ProvinceId');
    var DistrictId = document.getElementById('DistrictId');
    var WardId = document.getElementById('WardId');
    var StreetId = document.getElementById('StreetId');


    var Road = document.getElementById('Road');
    var RoadProvince = document.getElementById('RoadProvince');
    var RoadDistrict = document.getElementById('RoadDistrict');
    var RoadQuarter = document.getElementById('RoadQuarter');
    var RoadStreet = document.getElementById('RoadStreet');

    

    var Address = document.getElementById('Address');    


    RoadProvince.value = GetByProvinceId(ProvinceId.value);
    RoadDistrict.value = GetByDistrictId(DistrictId.value);
    RoadQuarter.value = GetByQuarterId(WardId.value);
    RoadStreet.value= GetById(StreetId.value);

    Road.value = RoadStreet.value + "," + RoadQuarter.value + "," + RoadDistrict.value + "," + RoadProvince.value;
    

}

function AddAddressProcess() {
    var OwnerCompany=document.getElementById('khongphai');
    if (OwnerCompany.checked == true) {
        OwnerCompany.value = "không";
    }
    else {
        OwnerCompany.value = "phải";
    }
    var Name = document.getElementById('Name');
    var Phone = document.getElementById('Phone');
    var Fax = document.getElementById('Fax');
    var Email = document.getElementById('Email');
    var Website = document.getElementById('Website');
    var TypeId = document.getElementById('TypeId');
    var StreetId = document.getElementById('StreetId');
    var Road = document.getElementById('Road');
    var Address = document.getElementById('Address');
   

    var RoadProvince = document.getElementById('RoadProvince');
    var RoadDistrict = document.getElementById('RoadDistrict');
    var RoadQuarter = document.getElementById('RoadQuarter');
    var RoadStreet = document.getElementById('RoadStreet');

    Road.value = Address.value + "," + RoadStreet.value + "," + RoadQuarter.value + "," + RoadDistrict.value + "," + RoadProvince.value;

    var Longitude = document.getElementById('Longitude');
    var Latitude = document.getElementById('Latitude');  

    var address = Address.value + "," + RoadDistrict.value + "," + RoadProvince.value;
    
    geocoder = new GClientGeocoder();

    geocoder.getLatLng(
        address,
        function (point) {
            if (!point) {
                alert(address + " không tìm thấy địa chỉ!");
            }
            else {

                Longitude.value = point.y;
                Latitude.value = point.x;
                var long = Longitude.value;
                var lat = Latitude.value;
                if (Name.value != "" && RoadStreet.value != "") {
                    AddAddress(OwnerCompany.value, Name.value, Phone.value, Fax.value, Email.value, Website.value, TypeId.value, StreetId.value, Road.value, Address.value, lat, long);
                }
                else {
                    alert('chưa nhập tên cty hoặc chưa chọn tên đường');
                }
            }
        })

    }
    function GetById(Id) {

        var webMethod = '/map.asmx/GetById'
        var parameters = "{'Id':'" + Id + "'}";

        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                document.getElementById('RoadStreet').value = msg.d;
                
            },
            error: function (e) {
                $("#errors1").html("Unavailable");
            }
        });
    };

    function GetByQuarterId(Id) {

        var webMethod = '/map.asmx/GetByQuarterId'
        var parameters = "{'Id':'" + Id + "'}";

        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //alert(msg.d);
                document.getElementById('RoadQuarter').value = msg.d;
                //$("#errors1").empty().html(msg.d);
            },
            error: function (e) {
                $("#errors1").html("Unavailable");
            }
        });
    };
    function GetByDistrictId(Id) {

        var webMethod = '/map.asmx/GetByDistrictId'
        var parameters = "{'Id':'" + Id + "'}";

        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                document.getElementById('RoadDistrict').value = msg.d;
            },
            error: function (e) {
                $("#errors1").html("Unavailable");
            }
        });
    };
    function GetByProvinceId(Id) {

        var webMethod = '/map.asmx/GetByProvinceId'
        var parameters = "{'Id':'" + Id + "'}";

        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                document.getElementById('RoadProvince').value = msg.d;
                
            },
            error: function (e) {
                $("#errors1").html("Unavailable");
            }
        });
    };
function InitFunctions() {
    $('a.poplight[href^=#]').click(function () {
        var popID = $(this).attr('rel'); //Get Popup Name
        var popURL = $(this).attr('href'); //Get Popup href to define size

        //Pull Query & Variables from href URL
        var query = popURL.split('?');
        var dim = query[1].split('&');
        var popWidth = dim[0].split('=')[1]; //Gets the first query string value

        //Fade in the Popup and add close button
        $('#' + popID).fadeIn().css({ 'width': Number(popWidth) }).prepend('<a href="#" class="close"><img src="Content/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');

        //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
        var popMargTop = ($('#' + popID).height() + 30) / 2;
        var popMargLeft = ($('#' + popID).width() + 80) / 2;

        //Apply Margin to Popup
        $('#' + popID).css({
            'margin-top': -popMargTop,
            'margin-left': -popMargLeft
        });

        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 

        return false;
    });

    //Close Popups and Fade Layer
    $('a.close, #fade').live('click', function () { //When clicking on the close or fade layer...
        $('#fade , .popup_block').fadeOut(function () {
            $('#fade, a.close').remove();  //fade them both out
        });
        return false;
    });

}